import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'
import constant from '@/common/constant/httpStatus'
import { axiosBaseUrl } from '@/common/config/baseConfig'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const instance = axios.create({
  timeout: 10000
})
instance.defaults.baseURL = axiosBaseUrl
// 正在进行中的请求列表 如果某个api存在这个数组里，说明该api暂时无法再次请求
const reqList = []
const alwaysAllowResList = ['/api/v1/dictionary/listDicByParentCode', '/api/v1/dictionary/listDicByAttach']

/**
 * 阻止重复请求（取消上一次请求）
 * @param {array} reqList - 请求缓存列表
 * @param {string} url - 当前请求地址
 * @param {function} cancel - 请求中断函数
 * @param {string} errorMessage - 请求中断时需要显示的错误信息
 */
const stopRepeatRequest = function (reqList, config, cancel, errorMessage) {
  const errorMsg = errorMessage || ''
  reqList.push({
    config,
    cancel
  })
  for (let i = 0; i < reqList.length - 1; i++) {
    if (reqList[i].config.url === config.url) {
      reqList[i].cancel(errorMsg)
      allowRequest(reqList, reqList[i].config.url)
    }
  }
}
/**
 * 允许某个请求可以继续进行
 * @param {array} reqList 全部请求列表
 * @param {string} url 请求地址
 */
const allowRequest = function (reqList, url) {
  for (let i = 0; i < reqList.length; i++) {
    if (reqList[i].config.url === url) {
      reqList.splice(i, 1)
      break
    }
  }
}

// request拦截器
instance.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers.authorization = store.getters.token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }

  let cancel
  // 设置cancelToken对象
  config.cancelToken = new axios.CancelToken(function (c) {
    cancel = c
  })
  if (alwaysAllowResList.indexOf(config.url) === -1) {
    // 阻止重复请求。当上个请求未完成时，取消上一次请求
    stopRepeatRequest(reqList, config, cancel, `${config.url} 请求被中断`)
  }

  return config
}, error =>
  Promise.reject(error)
)
let lock = false
let page = ''
// respone 拦截器
instance.interceptors.response.use(res => {
  allowRequest(reqList, res.config.url)

  if (res.status === 200) {
    const data = res.data
    if (constant.NO_LOGIN === data.code && !lock) {
      if (window.location.href.slice(window.location.href.lastIndexOf('#') + 1) === '/login' || lock || window.location.href.slice(window.location.href.lastIndexOf('#') + 1) === page) return
      page = window.location.href.slice(window.location.href.lastIndexOf('#') + 1)
      lock = true
      MessageBox.confirm('由于长时间未操作或已被强制下线，请重新登录', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        lock = false
        store.commit('user/SIGN_OUT')
        router.push({ path: '/login' })
      }).catch(e => {
        lock = false
      })
    } else if (constant.NO_LOGIN === data.code && lock) {
      return data
    } else if (constant.SUCCESS === data.code || lock || constant.LOGGED === data.code) {
      return data
    } else if (data.size) {
      return data
    } else {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return data
    }
    // returnCode(data)
  }
}, error => {
  if (axios.isCancel(error)) {
    return new Promise(() => {
    })
  } else {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
})

export default instance
